<?php

namespace ChanTienGioi\Backend\Controllers;

class AccessController extends \Phalcon\Mvc\Controller
{

    public function indexAction()
    {

        //Check Login
        if ($this->session->has("admin") && !empty($this->session->get("admin")))
        {
            return $this->response->redirect("backend");
        }

        //Set Style
        $this->assets->addCss($this->url->getBasePath() . 'public/css/admin/view/login.css', true);
        $this->assets->collection("inline")
                ->addJs($this->url->getBasePath() . 'public/js/admin/view/login.js');

        //Set View Params
        $this->view->header_title = "Login";
    }

    public function loginAction()
    {
        $response = array("status" => 0, "message" => "Username hoặc Password không đúng");

        $username = $this->request->getPost("username", "trim", false);
        $password = $this->request->getPost("password", "trim", false);
        if (!empty($username) && !empty($password))
        {
            $user_admin = \ChanTienGioi\Backend\Models\CtgUserAdmin::getUserByuserNameAndPassword($username, $password);
            if (!empty($user_admin))
            {
                $this->session->set("admin", $user_admin);
                $response["status"]  = 1;
                $response["message"] = "Login Thành Công";
            }
        }
        echo json_encode($response);
        exit();
    }

    public function logoutAction()
    {
        $this->session->remove("admin");
        return $this->response->redirect("backend/access");
    }

}
